<template>
  <div id="award">
    <div class="user-info">
      <img :src="sourceUrl+agentInfo.imageUrl" alt="">
      <div class="info-right">
        <p class="info-name">{{agentInfo.name}} </p>
        <!--<span>侍酒师</span>-->
        <div class="discrtion">
          {{agentInfo.selfInfo}}
        </div>
      </div>
    </div>
    <!--有钱就是任性-->
    <div class="line-box">
      <div class="line"></div>
      <span>有钱就是任性</span>
    </div>
    <!--输入打赏金额-->
    <div class="award-box">
      <div class="input-box">
        <span>￥:</span>
        <input type="number" style="padding-bottom:7px" placeholder="请输入打赏金额" @keyup="value=value.replace(/[^\d{1,}\.\d{1,}|\d{1,1}]/g, '')" v-model="inputMoney" v-on:input="inputNumber()">
      </div>
      <ul class="money-select">
        <template v-for="(item,index) in awardMoney">
          <li :class="{selected:isSelected==index}" @click="isSelected=index,selecteMoney(index)">{{item}}</li>
        </template>
      </ul>
    </div>
    <!--给侍酒师评论-->
    <div class="line-box">
      <div class="line"></div>
      <span>给侍酒师评论</span>
    </div>
    <ul class="user-comment">
      <li :key="index" v-for="(item,index) in userComment" @click="changeStatus(index)"><span
        :style="{background:(item.status?libg[Math.floor(Math.random()*10)]:'')}"
        :class="{select:item.status}">{{item.label}}</span></li>
      <!--<li style="background: #D43F3F" @click="addComment()">+</li>-->
    </ul>
    <div class="area-text">
      <textarea  maxlength="80" placeholder="添加备注（80字以内）" v-model="text"></textarea>
    </div>
    <div class="button-box">
      <button class="award-btn" type="button" @click="payBtn()">赏</button>
    </div>
    <div class="pay-pop" v-if="payPopShow">
      <div style="width:100%;height:100%;" @click="payPopShow=false"></div>
      <div class="pay-bg">
        <p class="price">￥{{isSelected<=3 ? awardMoney[isSelected] : inputMoney}}</p>
        <label><input name="pay" type="radio" value="0" v-model="payMode"/><span>微信支付</span></label>
        <label><input name="pay" type="radio" value="1" v-model="payMode"/><span>余额支付</span></label>
        <div class="pay-btn" @click="awardBtn()">支付</div>
      </div>
    </div>
    <TextPop v-if="orderSuccess" :textPop="popOrderSuccess"></TextPop>
  </div>
</template>

<script>
  import global from '../public/global.vue'
  import wx from 'weixin-js-sdk'
  export default {
    name: 'award',
    data() {
      return {
        sourceUrl:global.sourceUrl,
        agentInfo:{},//侍酒师信息
        awardMoney: [5.20, 13.14, 68.88],
        isSelected: 0,
        userComment: [],//用户评论标签内容
        libg: global.libg,
        labelSelect:[],//选中的标签
        text:'',//备注的内容
        inputMoney:'',//输入的金额
        orderSuccess:false,//打赏成功弹窗
        popOrderSuccess:"打赏成功",
        payPopShow:false,
        payMode:0,
      }
    },
    methods: {
      //选择打赏金额
      selecteMoney(idx) {
        this.inputMoney = this.awardMoney[this.isSelected]
      },
      inputNumber(){
        this.isSelected = 4;
        if(this.inputMoney !=''&& this.inputMoney.substr(0,1) == '.'){
          this.inputMoney="";
        }
        this.inputMoney = this.inputMoney.replace(/^0*(0\.|[1-9])/, '$1');//解决 粘贴不生效
        this.inputMoney = this.inputMoney.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
        this.inputMoney = this.inputMoney.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的
        this.inputMoney = this.inputMoney.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
        this.inputMoney = this.inputMoney.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
        if(this.inputMoney.indexOf(".")< 0 && this.inputMoney !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          if(this.inputMoney.substr(0,1) == '0' && this.inputMoney.length == 2){
            this.inputMoney= this.inputMoney.substr(1,this.inputMoney.length);
          }
        }

      },
      //添加评论
      addComment() {

      },
      payBtn(){
        this.payPopShow=true
      },
      //赏
      awardBtn(){
        if(this.payMode==1){
          this.checkAccount();
        }
        //选中的标签
        this.payPopShow = false;
        let pData = this.userComment;
        let label = '';
        pData.forEach((val, i) => {
          if(val.status){
            label+=val.label+',';
          }
        })
        if(pData.length>0){
          label = label.substring(0,label.length-1);
        }
        console.log(label);
        //获取备注
        let text = this.text;
        console.log(text);
        let agentId = this.$route.query.id
        let params = new URLSearchParams();
        let uid = global.getCookie("uid");
        let money = this.awardMoney[this.isSelected]
        if(this.isSelected==4){
          money = this.inputMoney
        }
        params.append("uid",uid);
        params.append("toUid",agentId)
        params.append("money",money)
        params.append("note",text);
        params.append("label",label)
        console.log(uid);console.log(agentId);console.log(money);
        this.$http({
          url:global.apiUrl + '/sendMoney/sendMoney',
          method:"post",
          data:params
        }).then(res => {
          let billNo = res.data.data.billNo;
          let params = new URLSearchParams();
          params.append('billNo', billNo);
          console.log(res);
          if(res.data.code==0){
            if(this.payMode==1){
              this.$http({
                method: "post",
                url: global.apiUrl + '/account/balanceAward',
                data: params,
              }).then(res => {
                if (res.data.code == 0) {
                  this.orderSuccess = true
                  setTimeout(()=>{
                    this.orderSuccess = false
                    this.$router.push({path: '/thanksLetter/?agentId='+agentId+"&label="+label+"&money="+money+"&note="+text});
                  },1500)
                }
                else{
                  alert("打赏失败");
                }
              }).catch(function (err) {
                console.error(err);
              })
            }else{
              this.$http({
                method: "post",
                url: global.apiUrl + '/pay/reward',
                data: params,
              }).then(res => {
                if (res.data.code == 0) {
                  this.appId = res.data.data.appId;
                  this.nonceStr = res.data.data.nonceStr;
                  this.paySign = res.data.data.paySign;
                  this.prepay_id = res.data.data.package;
                  this.timeStamp = res.data.data.timeStamp;
                  this.onBridgeReady(agentId,label,money,text);
                }
              }).catch(function (err) {
                console.error(err);
              })
            }
          }else{
          }
        })
      },
      //微信支付接口调用
      onBridgeReady(agentId,label,money,note) {
        let self = this;
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest', {
            "appId": self.appId, //公众号名称，由商户传入
            "timeStamp": self.timeStamp, //时间戳，自1970年以来的秒数
            "nonceStr": self.nonceStr, //随机串
            "package": self.prepay_id,
            "signType": "MD5", //微信签名方式：
            "paySign": self.paySign //微信签名
          },
          function (res) {
            console.log("--支付拉起--")
            console.log(JSON.stringify(res));
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              //$.toast(JSON.stringify(res));
              // var html = '<div class="weui-msg"><div class="weui-msg__icon-area"><i class="weui-icon-success weui-icon_msg"></i></div><div class="weui-msg__text-area"><h2 class="weui-msg__title">支付成功</h2></div></div>';
              //window.location = "/page/pay_success.html";
              self.isPop = false;
              this.orderSuccess = true
              setTimeout(()=>{
                this.orderSuccess = false
                this.$router.push({path: '/thanksLetter/?agentId='+agentId+"&label="+label+"&money="+money+"&note="+note});
              },1500)
              // $("#content-box").html(html);
              // $.toast("支付成功", "text");
              // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
              //alert("支付成功");
            } else {
              //$.toast(JSON.stringify(res));
//              $.toast("支付失败", "text");
              alert("支付失败");
            }
          }
        );

      },
      selectLabel(){

      },
      changeStatus(index){
        this.userComment[index].status=!this.userComment[index].status
      },
      checkAccount(){
        this.$http.get(global.apiUrl + "/account/checkAccount", {
          params: {money: this.inputMoney}
        }).then(res => {
          console.log(res.data);
          if (res.data.code == 0) {
            if(res.data.data.enough==0){
              alert("钱包余额不足！请选择其他支付方式")
            }else{

            }
          }
        }).catch(function (err) {
          console.error("Error:" + err);
        })
      }
    },
    created: function () {
      document.title = "侍酒师打赏";
      //获取侍酒师
      let agentId = this.$route.query.id
      this.$http.get(global.apiUrl + '/sommelier/sommelierInfo', {
        params: {
          id:agentId
        }
      }).then(res => {
        if (res.data.code == 0) {
          console.log(res.data.data);
          this.agentInfo = res.data.data
        }
      }).catch(function (err) {
        console.error(err);
      })
      //后台获取标签
      this.$http.get(global.apiUrl + '/label/getLabels', {
        params: {
          type:0
        }
      }).then(res => {
        if (res.data.code == 0) {
          console.log(res.data.data);

          let pData = res.data.data;
          pData.forEach((val, i) => {
            val.status = false;
          })
          this.userComment=pData
          console.log(this.userComment)
        }
      }).catch(function (err) {
        console.error(err);
      })
      //默认输入金额
      this.inputMoney = this.awardMoney[this.isSelected]
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
  #award {
    padding: 10px;
    background: #f3f3f3;
    .user-info {
      width: 100%;
      img {
        width: 5rem;
        height: 5rem;
        border-radius: 50%;
        margin-right: 10px;
        vertical-align: middle;
      }
      .info-right {
        display: inline-block;
        width: 64%;
        overflow: hidden;
        font-size: 1rem;
        vertical-align: middle;
        color: #aaa;
        .info-name {
          color: #333;
          span {
            font-size: 0.7rem;
            padding: 0 8px;
            background: #FB3C3D;
            border-radius: 30px;
            color: #fff;
            font-weight: 300;
          }
        }
        .discrtion {
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          height: 2rem;
          margin-top: 4px;
          font-size: 0.8rem;
        }
      }
    }
    .line-box {
      position: relative;
      width: 100%;
      padding: 10px 0;
      margin-top: 10px;
      line-height: 2rem;
      .line {
        widdth: 100%;
        height: 0;
        border-top: 1px solid #ddd;
        margin-top: 10px;
      }
      span {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        margin: 4px auto;
        width: 90px;
        display: inline-block;
        background: #f3f3f3;
        font-size: 0.7rem;
        color: #aaa;
        text-align: center;
      }
    }
    /*输入打赏金额*/
    .award-box {
      width: 100%;
      margin: 10% auto;
      .input-box {
        height: 60px;
        line-height: 40px;
        font-size: 1.5rem;
        color: #D43F3F;
        margin-left: 2rem;
        input {
          width:60%;
          border: none;
          outline: none;
          font-size: 1.5rem;
          color:#ff0000;
          background: #f3f3f3;
        }

      }
      .money-select {
        width: 100%;
        padding: 10px;
        display: flex;
        justify-content: space-between;
        li {
          width: 60px;
          height: 36px;
          line-height: 36px;
          border: 1px solid #aaa;
          text-align: center;
          border-radius: 4px;
          font-size: 0.9rem;
          color: #777;
        }
        .selected {
          border-color: #E69191;
          background: #F2C5C5;
          color: #D85555;
        }
      }
    }
    /*评论*/
    .user-comment {
      width: 100%;
      padding-top: 10px;
      display: flex;
      flex-wrap: wrap;
      /*li {*/
        /*height: 1.5rem;*/
        /*line-height: 1.5rem;*/
        /*font-size: 0.8rem;*/
        /*color: #fff;*/
        /*!*background: #F680B8;*!*/
        /*text-align: center;*/
        /*margin-left: 10px;*/
        /*margin-bottom: 10px;*/
        /*border-radius: 30px;*/
        /*padding: 0 10px;*/
        /*.select {*/
          /*border-color: transparent;*/
          /*color: #fff;*/
        /*}*/
      /*}*/
      li {
        margin-right: 10px;
        margin-bottom: 10px;
        span {
          font-size: 0.85rem;
          color: #666;
          padding: 4px 10px;
          border: 1px solid #aaa;
          border-radius: 30px;
        }
        .select {
          border-color: transparent;
          color: #fff;
        }
      }
      /*li:last-child {*/
        /*font-size: 1.3rem;*/
      /*}*/
    }
    /*添加备注*/
    .area-text {
      width: 100%;
      margin: 10px auto;
      textarea {
        width: 100%;
        font-size: 0.8rem;
        background: #f3f3f3;
        outline: none;
        resize: none;
        border: none;
      }
    }
    /*赏*/
    .button-box {
      width:100%;
      text-align: center;
      .award-btn {
        width: 60px;
        height: 60px;
        line-height: 60px;
        text-align: center;
        margin: 40px auto 0;
        border-radius: 50%;
        font-size: 2rem;
        color: #fff;
        border: none;
        outline:none;
        background: #D43F3F;
      }
    }
    /*提交弹窗*/
    .pay-pop {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, .5);
      .pay-bg {
        position: absolute;
        top: 30%;
        left: 0;
        right: 0;
        width: 90%;
        margin: auto;
        background: #fff;
        padding: 5% 10%;
        border-radius: 6px;
        .price {
          height: 3rem;
          line-height: 3rem;
          font-size: 1.5rem;
          text-align: center;
          margin-bottom: 10px;
        }
        label {
          display: block;
          height: 2rem;
          line-height: 2rem;
          text-align: center;
          border-bottom: 1px solid #eee;
          font-size: 1rem;
          font-weight: inherit;
          input {
            -webkit-appearance: radio;
            width: 20px;
            height: 20px;
            vertical-align: middle;
            margin: 0;
          }
          span {
            margin-left: 10%;
            vertical-align: middle;
          }
        }
        .pay-btn {
          width: 100%;
          height: 2rem;
          line-height: 2rem;
          font-size: 1rem;
          color: #fff;
          background: #d44242;
          border-radius: 6px;
          text-align: center;
          margin-top: 20px;
        }
      }
    }
  }
</style>
